// pages/List/List.js
var widthScreen;
var OpenId;
var back = "";
var isLoadimg = true;
var app = getApp();
export function $parseVars2Str(...args) {
  // return Array.prototype.join.call(arguments , ',');
  return args.join(",")
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoheight: "",
    title: "",
    introduction: "",
    // imgHeight: "",
    leftrow: "",
    leftcolumn: "",
    time: null,
    day: "",
    city: "",
    isHide:false,
    weather: "",
    steps: [{
      imgHeight: "",
      id: 0,
      txt: "",
      imageUrl: "",
      imgExist: 0,
    }, ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(option) {

    let lists = this.data.steps;
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        widthScreen = res.windowWidth;
        that.setHeight();
      },
    })

    this.setData({
      leftrow: (widthScreen * 0.8 - 50) * 0.5,
      leftcolumn: (widthScreen * 0.8 - 16) * 0.5
    })
    let Time = option.time;
    let openid = option.openid;
    OpenId = openid;
    if (OpenId == undefined || OpenId == null || OpenId.length == 0) {
      wx.cloud.callFunction({
        name: 'getOpenid',
        success: res => {
          OpenId = res.result.openid;
        }
      })
    }

    console.log(OpenId);
    console.log(Time)
    if (Time != null || Time != undefined) {
      console.log(Time);
      this.setData({
        time: Time
      })
      this.getData(openid);
    } else {
      this.getLocation();
    }
    that.setData({
      isHide:true
    })
  },
  getLocation: function() {
    let that = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function(res) {
              if (res.cancel) {
                console.log("拒绝授权")
              } else if (res.confirm) {
                wx.openSetting({
                  success: function(dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      console.log("授权成功")
                      that.getWeather()
                    } else {
                      console.log("授权失败")
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          that.getWeather()
        } else {
          that.getWeather()
        }
      }
    })
  },
  getWeather: function() {
    var that = this;
    wx.getLocation({
      altitude: 'altitude',
      complete: (res) => { },
      fail: (res) => { },
      highAccuracyExpireTime: 0,
      isHighAccuracy: true,
      success: ({
        //longitude:lg, 给longitude变量取别名为lg
        longitude: lg,
        latitude: la
      }) => {
        //使用腾讯地图获取当前地址  
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/',
          data: {
            location: $parseVars2Str(la, lg),
            key: 'SGCBZ-ETMWJ-REVFL-KWPFR-CO34Z-75BIV'
          },
          complete: (res) => { console.log(res) },
          success: (result) => {
            console.log(result.data.result.address)
            that.setData({
              city: result.data.result.address,
            })
          },
        })

        // this.setData({
        //   location:$parseVars2Str(lg , la)
        // })
      },
      type: 'gcj02',
    })
     
  },
  getData: function(openid) {
    let that = this;
    const db = wx.cloud.database();
    db.collection("Menu").where({
      time: parseInt(this.data.time),
    }).field({
      introduction: true,
      title: true,
      time: true,
      steps: true,
      _id: false,
      day: true,
      city: true,
      weather: true,
    }).get().then(function(res) {
      console.log(res.data[0])
      that.setData({
        title: res.data[0].title,
        introduction: res.data[0].introduction,
        time: res.data[0].time,
        day: res.data[0].day,
        city: res.data[0].city,
        weather: res.data[0].weather,
        steps: res.data[0].steps,
      })
      // console.log(that.data.city)
      if ((that.data.city == "" && that.data.day == "" && that.data.weather == "") || (that.data.city == undefined && that.data.day == undefined && that.data.weather == undefined)) {
        console.log(that.data)
        that.getLocation();
      }
      that.setImg(openid);
    })

  },
  setHeight: function() {
    let lists = this.data.steps;
    console.log(widthScreen);
    for (let i = 0; i < lists.length; i++) {
      lists[i].imgHeight = widthScreen * 0.9 * (3 / 4);
    }
    this.setData({
      steps: lists,
    })
  },
  imageErr: function(e) {
    if (isLoadimg) {
      console.log("err");
      console.log(e)
      let that = this;
      let lists = that.data.steps;

      wx.cloud.downloadFile({
        fileID: 'cloud://gerencaipu-caiminghong.6765-gerencaipu-caiminghong-1300563066/images/menu_' + OpenId + '_' + that.data.time + '_' + e.currentTarget.dataset.chooseid + '.jpg',
        success: function(res) {
          console.log(res.tempFilePath);
          lists[e.currentTarget.dataset.chooseid].imageUrl = "" + res.tempFilePath;
          that.setData({
            steps: lists,
          })
        },
        fail: function(err) {
          console.log(err);
        }
      })
    }
    isLoadimg = true;
  },
  setImg: function(openid) {
    this.setHeight();

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  onPullDownRefresh() {
    console.log(this.data)
    let that = this;
    let lists = that.data.steps;
    for (let i = 0; i < lists.length; i++) {
      if (lists[i].imageUrl == "") {
        continue;
      }
      wx.cloud.downloadFile({
        fileID: 'cloud://gerencaipu-caiminghong.6765-gerencaipu-caiminghong-1300563066/images/menu_' + OpenId + '_' + that.data.time + '_' + i + '.jpg',
        success: function(res) {
          console.log(res.tempFilePath);
          lists[i].imageUrl = "" + res.tempFilePath;
          that.setData({
            steps: lists,
          })
        },
        fail: function(err) {
          console.log(err);
        }
      })
    }
    wx.stopPullDownRefresh();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let lists = this.data.steps;
    this.setData({
      steps: lists,
    })
  },
  bindload: function(ev) {
    let scale = ev.detail.height / ev.detail.width;
    let lists = this.data.steps;
    lists[ev.currentTarget.dataset.chooseid].imgHeight = widthScreen * 0.9 * scale;
    this.setData({
      steps: lists,
    })
  },

  bindCPtitleinput: function(e) {
    console.log(e.detail.value)
    this.setData({
      title: e.detail.value
    })
  },
  bindCPintroduction: function(e) {
    console.log(e.detail.value)
    this.setData({
      introduction: e.detail.value
    })
  },
  bindlinechange: function(e) {
    console.log(e);
    this.setData({
      autoheight: e.detail.height + 18,
    })
  },
  btnChooseImg: function(e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        let lists = that.data.steps;
        lists[e.currentTarget.id].imageUrl = res.tempFilePaths[0];
        that.setData({
          steps: lists,
        })
      },
      fail: function(res) {
        wx.showModal({
          title: '问',
          content: '是否去掉这张图',
          success: function(res) {
            if (res.confirm) {
              isLoadimg = false;
              let lists = that.data.steps;
              lists[e.currentTarget.dataset.chooseid].imageUrl = "";
              lists[e.currentTarget.dataset.chooseid].imgHeight = widthScreen * 0.9 * (3 / 4);
              that.setData({
                steps: lists,
              })
            } else {

            }
          }
        })

      },
      complete: function(res) {

      }
    })

  },
  btnAddStep: function() {
    var list = [];
    list = this.data.steps;
    var len = list.length;
    list.push({
      id: len,
      txt: "",
      imageUrl: "",
      imgHeight: widthScreen * 0.9 * (3 / 4),
    });
    this.setData({
      steps: list
    })
  },

  bindCPstep: function(e) {
    let lists = this.data.steps;
    lists[e.currentTarget.id].txt = e.detail.value;
    this.setData({
      steps: lists,
    })
  },
  getLocalTime:function(nS) {

    return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/, ' ');

  },
  btnClick1: function(e) {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    console.log(prevPage.data.Lists);
  },
  btnClick: function(e) {
    let lists = this.data.steps;
    wx.showLoading({
      title: '上传中',
    })
    let uptime = Date.parse(new Date());
    if (this.data.time == null) {
      this.data.time = uptime;
      this.setData({
        time: uptime
      })
    }
    var that = this;
    var hideIndex=0;
    for (let i = 0; i < lists.length; i++) {
      if (lists[i].imageUrl.length != 0) {
        hideIndex = i;
      }
    }
    if (hideIndex == 0 && lists[0].imageUrl.length == 0) {
      that.dbManage();
      that.hide();
      return;
    }
    for (let i = 0; i < lists.length; i++) {
      if (lists[i].imageUrl.length != 0) {
        wx.cloud.uploadFile({
          cloudPath: "images/menu_" + OpenId + "_" + that.data.time + "_" + i + ".jpg",
          filePath: lists[i].imageUrl,
          success: function(rec) {
            console.log(i);
            console.log(rec)
            // console.log(rec.fileID);
            if (i == hideIndex) {
              that.dbManage();
              that.hide();
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              })
            }
          },
          fail: function(res) {
            console.log("error:" + res)
            that.hide();
          },
        })
      }
    }
  },
  hide: function() {
    wx.hideLoading();
  },
  
  dbManage: function() {
    var stepsList = [];
    var lists = this.data.steps;
    let that = this;
    for (let i = 0; i < lists.length; i++) {
      if (lists[i].imageUrl == "") {
        lists[i].imgExist = 0
      } else {
        lists[i].imgExist = 1
      }
    }
    console.log(that.getLocalTime(that.data.time))
    stepsList = {
      title: that.data.title,
      introduction: that.data.introduction,
      steps: lists,
      status: 1,
      time: that.data.time,
      listHide: false,
      day: that.getLocalTime(that.data.time),
      weather: that.data.weather,
      city: that.data.city,
    };
    //获取上一页面的Page
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];

    const db = wx.cloud.database();
    db.collection("Menu").where({
      time: that.data.time
    }).get().then(function(res) {
      //true是添加，false是更新                                                       
      if (res.data.length == 0) {
        let lists = prevPage.data.Lists;
        let List = [];
        List[0] = stepsList;
        for (let i = 0; i < lists.length; i++) {
          List[i + 1] = lists[i];
        }

        prevPage.setData({
          Lists: List,
        })

        db.collection("Menu").add({
          data: stepsList
        }).then(com => {
          console.log(com)
          wx.navigateBack({
            delta: 1
          })
        })
      } else {
        console.log(res.data)
        let lists = prevPage.data.Lists;
        for (let i = 0; i < lists.length; i++) {
          if (lists[i].time == that.data.time) {
            lists[i].title = that.data.title;
          }
        }
        prevPage.setData({
          Lists: lists,
        })
        // console.log(stepsList)
        wx.cloud.callFunction({
          name: "runDB",
          data: {
            db: "Menu",
            type: "update",
            condition: {
              _id: res.data[0]._id,
            },
            data: stepsList
          },
          success: res => {
            console.log(res);
            wx.navigateBack({
              delta: 1
            })
          },
          fail: err => {
            console.error("error:" + err)
          }
        })
        // db.collection("Menu").doc(res.data[0]._id).update({
        //   data: stepsList
        // }).then(e => {
        //   console.log(e)
        //   wx.navigateBack({
        //     delta: 1
        //   })
        // })
      }
    })
  },
})